//
// Created by konglinglong on 2020/9/21.
//

#ifndef OSI_5G_TESTS_LIB_COMMDEF_H_
#define OSI_5G_TESTS_LIB_COMMDEF_H_

#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include "../../src/o5gcn/include/debugCode.h"
#include "../../src/o5gran/include/debugCode.h"
#include "../../src/o5gue/include/debugCode.h"

#define RAN_L1_MEM_SIZE_MAX       (8 * 1024 * 1024)
#define RAN_L2_CU_MEM_SIZE_MAX    (8 * 1024 * 1024)
#define RAN_L2_DU_MEM_SIZE_MAX    (8 * 1024 * 1024)
#define RAN_L3_MEM_SIZE_MAX       (8 * 1024 * 1024)
#define RAN_OM_MEM_SIZE_MAX       (8 * 1024 * 1024)

#define O5G_RAN_CONFIG_FILE_PATH_4_TEST  O5G_SOURCE_DIR "/tests/app/config/o5gran/"

extern uint32_t gCnDebugCodeSave[CN_DEBUG_CODE_BUTT];
extern uint32_t gRanDebugCodeSave[RAN_DEBUG_CODE_BUTT];
extern uint32_t gUeDebugCodeSave[UE_DEBUG_CODE_BUTT];

#define TEST_LOG(fmt, args...) \
do {\
    struct tm tm;\
    struct timeval tv;\
    uint32_t offset;\
    char buffer[4096];\
    gettimeofday(&tv, NULL);\
    offset = strftime(buffer, sizeof(buffer), "[%y-%m-%d %X", localtime_r(&tv.tv_sec, &tm));\
    offset += snprintf(buffer + offset, sizeof(buffer) - offset, ".%03ld][TEST] " fmt, tv.tv_usec / 1000, ##args);\
    printf("%s", buffer);\
} while(0)

void UT_SAVE_ALL_DBG_CODE();
uint32_t UT_GET_DBG_CODE(int32_t app, int32_t dc);
uint32_t UT_GET_SAVE_DBG_CODE(int32_t app, int32_t dc);

#define UT_WAIT_EXPECT_TIME(opra, expected, expr, timeoutSec) \
do {\
    uint32_t utLoop = 0;\
    while (utLoop++ < timeoutSec * 100)\
    {\
        if ((expected) opra (expr))\
        {\
            break;\
        }\
        usleep(10000);\
    }\
    if (!((expected) opra (expr)))\
    {\
        TEST_LOG("UT_WAIT_EXPECT : %s[%d] %s %s[%d]\n", #expr, expr, #opra, #expected, expected);\
    }\
    REQUIRE((expected) opra (expr));\
} while(0)

#define UT_WAIT_EXPECT(opra, expected, expr)  UT_WAIT_EXPECT_TIME(opra, expected, expr, 5)

#define UT_WAIT_DBG_CODE_ABS_TIME(val, app, dc, timeoutSec) \
do {\
    uint32_t utLoop = 0;\
    while (utLoop++ < timeoutSec * 100)\
    {\
        if ((val) == UT_GET_DBG_CODE(app, dc))\
        {\
            break;\
        }\
        usleep(10000);\
    }\
    if ((val) != UT_GET_DBG_CODE(app, dc))\
    {\
        TEST_LOG("UT_WAIT_DBG_CODE : %s:%s = %d, expected : %d\n", #app, #dc, UT_GET_DBG_CODE(app, dc), (val));\
    }\
    REQUIRE((uint32_t)(val) == UT_GET_DBG_CODE(app, dc));\
} while(0)

/* 等待调试码，绝对值absolute */
#define UT_WAIT_DBG_CODE_ABS(val, app, dc)  UT_WAIT_DBG_CODE_ABS_TIME(val, app, dc, 5)

/* 等待调试码，增加值increasement */
#define UT_WAIT_DBG_CODE_INC(inc, app, dc)  UT_WAIT_DBG_CODE_ABS_TIME(UT_GET_SAVE_DBG_CODE(app, dc) + (inc), app, dc, 5)

#endif //OSI_5G_TESTS_LIB_COMMDEF_H_
